user.admin = liwe.module ( "user.admin", null, "Gestione utenti" );

user.admin._modules = null;
user.admin.admin_man = null;

user.admin._curr_uid = 0;
user.admin._id_login= [];
user.admin._right_top_div = 'user-admin-perms';
user.admin._left_top_am_div = 'user-admin-users';
user.admin._left_bot_div = 'user-admin-groups';

user.admin._groups_on = null;

user.admin._templates = {
	"user-list-radio" : '<input type="radio" value="%(uid)s" name="x_user" onchange="user.admin._set_curr_user(this.value)" />',
	"user-perm-check" : '<input type="checkbox" value="%(value)s" %(_checked)s /> %(label)s <br />',
	"user-perm-apply" : '<button onclick="user.admin._set_perms()">Applica</button>'
};

user.admin._admin_manager_init = function ( dest_div )
{
	if ( ! user.admin.admin_man )
	{
		user.admin.admin_man = new AdminManager ( { 
			'name' : 'users-list',
			'dest_res': dest_div,
			'list_action': "user.admin.list_new",
			'del_action': 'user.admin.del' ,
			'filter_form' : user.admin._filter_form,
			'filter_form_name' : 'user-filter-form',
			'glob_menu_actions': [
				{ action_name: 'enabled_all', img_src: '/modules/user/gfx/user_green.png', label: 'Abilita', func: user.admin.enabled },
				{ action_name: 'disabled_all', img_src: '/modules/user/gfx/user_gray.png', label: 'Disabilita', func: user.admin.disabled }
			],
			'mod_menu_actions': [
				 { func: 'user.admin.add ()', 'class' : 'user-add-user' , label: 'Aggiungi utente' }
                                                        ],
			'templates' : {
			      	"del_obj" : '<div class="user_del_icon" title="Elimina" onclick="AdminManager.row_action(\'%(_id)s\',\'del_item\', \'%(_am_name)s\' )" ></div>',
				"edit_obj" : '<div class="user_edit_icon" title="Modifica" onclick="AdminManager.row_action(\'%(_id)s\',\'edit_item\',\'%(_am_name)s\')"></div>'
				}
		} );

		user.admin.admin_man.set_row_fields ( [ 
							[ "UID", "uid" ], 
							[ "Login / e-mail", "_txt" ], 
							[ "Data creazione", "_created" ], 
							[ "Abilitato", "_enabled" ],
							[ "Last log", "_last_log" ]
						     ] );

		user.admin.admin_man.set_row_actions ( [ 
							[ '<img border="0" src="/modules/user/gfx/key.png" alt="Modifica password" title="Modifica password" />', "modify_pwd" ],
							[ '<img border="0" src="/modules/user/gfx/setting_tools.png" alt="Setta i permessi"  title="Setta i permessi"/>', "set_perms" ]
						] );

		user.admin.admin_man.cbacks [ 'row_manip' ] = user.admin.list_row_manip;

		user.admin.admin_man.cbacks [ 'edit_item' ] = function ( id ) { user.admin.edit ( user.admin._right_top_div, id ); };
		user.admin.admin_man.cbacks [ 'del_item' ]  =  function ( id ) { user.admin.del ( user.admin._right_top_div, id ); };
	
		// custom actions
		user.admin.admin_man.cbacks [ 'modify_pwd' ] =  function ( id ) { user.admin._modify_pwd ( user.admin._right_top_div, id ); };
		user.admin.admin_man.cbacks [ 'set_perms' ]  =  function ( id ) { user.admin._set_perms ( user.admin._right_top_div, id, 'user' ); };
	}
};

user.admin._filter_form = function ( dest_div, name,  action )
{
	if ( ! action ) action = "user.admin._filter_apply();";
	var am = user.admin.admin_man;
	if ( ! name ) name = am._filter_form_name;
	var f = new liwe.form.instance ( name );
	f.label ( { value: 'Login:' } );
	f.text ( { name: 'login' } );
	f.label ( { value: 'Email:' } );
	f.email ( { name: 'email' } );
	/*FIXME: all set , just find a way to disable fom calendar fields when not needed
	f.label ( { value: 'Creato:' } );
	f.calendar ( { name: 'created' } );
	f.label ( { value: 'Ultimo log-in:' } );
	f.calendar ( { name: 'last_log' } );
	*/
	f.label ( { value: 'Abilitato:' } );
	f.checkbox ( { name: 'enabled', value : 1 , checked : true } );	
	f.button ( { value: "Applica Filtro", "class": 'green',  onclick: action, nonl: true } );
	f.button ( { value: 'Reset filtri', 'class' : 'yellow', onclick: function ( f ) { f.clear (); } } );
	f.set ( dest_div );
};

user.admin._filter_apply = function ()
{
	user.admin.admin_man.search_start ();
};

user.admin.add = function ( dest_div )
{
	if ( user.admin._groups_on ) group.admin._clear_group_divs ();
	if ( ! $( 'user-admin-users' ) ) user.admin.create_layout ();
	if ( ! dest_div ) dest_div = user.admin._right_top_div;
	user.admin._curr_uid = null;

	user.admin.create ( dest_div );
};

user.admin.enabled = function ( uids )
{
	if ( ! uids ) return;

	user.admin._set_enabled ( uids, 1 );
};

user.admin.disabled = function ( uids )
{
	if ( ! uids ) return;

	user.admin._set_enabled ( uids );
};


user.admin._set_enabled = function ( ids, en )
{
	if ( ! en ) en = 0;

	user.admin.ajax ( { action: 'user.admin.set_enabled', uids: ids.join ( "|" ), enabled: en }, function ( v )
	{
		user.admin.list_users ();
	} );
};

user.admin.list_row_manip = function ( ds, row )
{
	row [ '_id' ] = row [ 'uid' ];
	row [ '_txt' ] = '<b>' + row [ 'login' ] + '</b> ' + row [ 'email' ];

	row [ '_created' ] = '&nbsp;';
	if ( row.get ( 'created' ) )
		row [ '_created' ] = liwe.utils.date2str ( row [ 'created' ], 1 );

	row [ '_last_log' ] = '&nbsp;';
	if ( row.get ( 'last_log' ) )
		row [ '_last_log' ] = liwe.utils.date2str ( row [ 'last_log' ], 1 );

	user.admin._id_login [ row [ 'uid' ] ] = row [ 'login' ];
	//if ( row.get ( '_img' ) )
	//	row [ '_txt' ] = String.formatDict ( user.admin.templates [ 'admin_txt_row' ], row );
};

user.admin._modify_pwd = function ( dest_div, uid )
{
	console.debug ( dest_div );
	if ( user.admin._groups_on ) group.admin._clear_group_divs ();
	user.admin._curr_uid = uid;

	$( dest_div, String.formatDict ( user.templates [ 'user_create' ], { title: 'Modifica Password' } ) );

	var f = new liwe.form.instance ( "user-change-pwd-frm" );

	f.hidden ( 'uid', uid );
	f.hidden ( 'action', "user.admin.change_pwd" );

	f.password ( { name: 'pwd', label: 'Password', mandatory: true } );
	f.password ( { name: 'pwd2', label: 'Password (conferma)', mandatory: true } );
	f.button ( { name: 'btn_save', value: 'Salva', onclick: "user.admin.change_pwd_done()" } );

	f.set ( 'user_cnt_form' );
};

user.admin.change_pwd_done = function ()
{
	var f = liwe.form.get ( "user-change-pwd-frm" );

	if ( ! f.check () ) return;

	var dct = f.get_values ();

	if ( dct [ 'pwd' ] != dct [ 'pwd2' ] )
	{
		alert ( "La password non corrisponde" );
		f.set_focus ( "pwd" );
		return;
	}

	user.admin.ajax ( dct, function ( v )
	{
		$ ( user.admin._right_top_div ).innerHTML = '';
	} );

};

user.admin.edit = function ( dest_div, id )
{
	if ( user.admin._groups_on ) group.admin._clear_group_divs ();
	user.admin._curr_uid = id;

	user.admin.ajax ( { action: "user.admin.get", uid: id }, function ( v )
	{
		user.admin.create ( dest_div, v [ 'user' ], true );
	});
};

user.admin.create = function ( dest_div, dct )
{
	if ( ! dct ) dct = {};
	if ( user.admin._groups_on ) group.admin._clear_group_divs ();

	var uid = dct.get ( 'uid', '' )
	var data = { "title" : ( uid ? "Modifica utente " + user.admin._id_login [ uid ] : "Creazione nuovo utente" ) };

	$( dest_div, String.formatDict ( user.templates [ 'user_create' ], data ) );

	var f = new liwe.form.instance ( "user-frm" );

	f.hidden ( 'uid', uid );
	f.hidden ( 'action', "user.admin.create" );

	f.text ( { name: 'login', label: 'Login', mandatory: true, value: dct.get ( 'login', '' ) } );
	f.text ( { name: 'email', label: 'Email', mandatory: true, value: dct.get ( 'email', '' ) } );

	f.password ( { name: 'pwd', label: 'Password'  } );
	f.password ( { name: 'pwd2', label: 'Password (conferma)' } );

	f.checkbox ( { name: 'enabled', label: 'Abilitato', value: 1, checked: dct.get ( 'enabled', 0 ) } );

	f.button ( { name: 'btn_save', value: 'Salva', onclick: "user.admin.create_done()" } );

	f.set ( "user_cnt_form" );
};

user.admin.create_done = function ()
{
	var f = liwe.form.get ( "user-frm" );

	if ( ! f.check () ) return;

	var dct = f.get_values ();

	if ( dct [ 'pwd' ] != dct [ 'pwd2' ] )
	{
		alert ( "La password non corrisponde" );
		// f.set_focus ( "pwd" );
		return;
	}

	user.admin.ajax ( dct, function ( v )
	{
		user.admin.list_users ();
	} );
};

user.admin.del = function ( dest_div, id )
{
	if ( ! id ) return;

	user.admin._curr_uid = id;

	if ( confirm ( "Sei sicuro di voler eliminare questo utente?" ) )
	{
		user.admin.ajax ( { action: "user.admin.delete", ids: id }, function ( v ) 
		{
			user.admin._curr_uid = 0;
			user.admin.list_users () ;
		} );
	}
};

user.admin.list_users = function ()
{
	if ( ! $( 'user-admin-users' ) ) user.admin.create_layout ();
	user.admin.admin_man.show_list ();
	//FIXME: 
	if ( user.admin._groups_on ) 
	{
		group.admin._clear_group_divs ();
		group.admin.admin_man.show_list ();
	}
};

user.admin._make_perms_form = function ( dest, id, type, msg )
{
	var cback, tback , mod_div;
	var mods_lst = [], mods_str = user.admin._modules_str; 

	var vals = {
			action: 'system.ajax.module_get_all_perms',
			uid: id,
			perms_type: type,
			module_names: mods_str
		   };

	$( dest, String.formatDict ( user.templates [ 'user_create' ], { title: msg } ) );

	user.admin.acc_mods.clear ();
	user.admin._tmp_group_cnt = {};

	tback = cback = function () 
		{ 
			user.admin.acc_mods.render ( 'user_cnt_form' ); 
			user.admin._set_all_perms ( type );	
		};
	if ( type == 'user' && user.admin._groups_on ) cback = function () { user.admin._set_acc_content ( vals, id, type, tback ); }; 

	user.admin._set_acc_content ( vals, id, type, cback );
};

user.admin._set_acc_content = function ( vals, id, type, cback )  
{
	if ( user.admin._groups_on && type == 'user' && user.admin._tmp_group_cnt.count () < 1 ) 
	{
		vals [ 'perms_type' ] = 'group';
	} else {
		vals [ 'perms_type' ] = type;
	}

	user.admin.ajax ( vals, function ( data )
	{
		if ( ! data.get ( 'perms' ) ) return;
		var perms = data [ 'perms' ];
		var keys = perms.keys ().sort ();
		var res = '';

		keys.iterate ( function ( k )
		{
			v = perms [ k ];

			// crea il testo per i permessi del gruppo
			if ( type == 'user' && vals [ 'perms_type' ] == 'group' )
			{
				//user.admin._tmp_group_cnt [ k ] = user.admin._list_perms_txt ( k, v, id, 'group' );
				user.admin._tmp_group_cnt [ k ] = user.admin._frmt_inherit_perms ( id, k );
				return;
			}
			var cnt = new String.buffer ();
			// crea il contenuto per l'accordion ed aggiunge l'elemento	
			cnt.add ( user.admin._list_perms ( k, v, id, type ) );

			if ( type == 'user' ) cnt.add ( user.admin._tmp_group_cnt [ k ] );

			res = cnt.toString ();
			if ( res )
				user.admin.acc_mods.add_item ( { txt: k, content: res } );
			
		} );

		if ( cback ) cback ();
	} );
};

user.admin._frmt_inherit_perms = function ( uid, module_name, cback )
{
	if ( ! group.admin._u2g ) return;
	var cache = group.admin._u2g.get ( uid );
	var out = new String.buffer ();
	var jperms, cked, mod_perms = user.admin._modules_perms [ module_name ];

	cache.iterate ( function ( v, k )
				{
					jperms = v.perms [ module_name ];
					if ( jperms.count () < 1 ) return;
					out.add ( String.formatDict ( user.templates [ 'user-perms-title' ], { title: k } ) );
					jperms = '|' + jperms.join ( '|' ) + '|';
					mod_perms.iterate ( function ( perm )
								{
									cked = ( jperms.indexOf ( '|' + perm.value + '|' ) >= 0 ) ? true : false ;
									if ( cked ) out.add ( String.formatDict ( user.templates [ 'user-perms-txt' ] , perm ) ); 
								} );
				} );
	if ( ! cback ) return out.toString ();
	cback ( out, module_name );

};

user.admin._list_perms = function ( module_name, data, id, type )
{
	var perms = data;
	var jperms = '|' + perms.join ( '|' ) + '|';
	var cked, mod_perms = user.admin._modules_perms [ module_name ];

	if ( mod_perms.count () < 1 ) return '';
	var f = new liwe.form.instance ( "user-perms-" + module_name );
	f.hidden ( "module_name", module_name );
	if ( type == 'user' )
		f.hidden ( "uid", user.admin._curr_uid );
	if ( type == 'group' )
		f.hidden ( "gid", group.admin._curr_gid );
	mod_perms.iterate ( function ( perm, k ) 
				{
					cked = ( jperms.indexOf ( '|' + perm.value + '|' ) >= 0 ) ? 1 : 0 ;
					//console.debug ( "user.admin._list_perms - iterate %s/perms [ %s ] = %s - perms = %o " , module_name, perm.value, cked, perms );
					f.checkbox ( { name: 'perm:' + perm.value, label: perm.label, value: perm.value, checked: cked } ); 
				} );

	f.button ( { value: "Applica", onclick: "user.admin._set_perms_save( '" + module_name + "', '" + type + "' )" } );

	return f.get ();
};

user.admin._set_all_perms = function ( type )
{
	var cnt = $( 'user_cnt_form' );
	if ( ! cnt ) return;
	var div = document.createElement ( 'div' );
	div.setAttribute ( 'id', 'user-set-all-perms' );
	var btn = document.createElement ( 'button' );
	btn.setAttribute ( 'class', 'green' );
	btn.setAttribute ( 'onclick', "user.admin._set_all_perms_save ( '" + type + "' );" );
	btn.innerHTML = 'Aggiorna tutti i permessi'; 
	cnt.appendChild ( div );
	$( 'user-set-all-perms' ).appendChild ( btn );
};

user.admin._set_all_perms_save = function ( type, cback )
{
	var f, updated = [];
	if ( ! cback )
	{
		cback = function ( resp )
		{
			user.admin._set_perms ( user.admin._right_top_div, user.admin._curr_uid ); 
			var str = updated.join ( ', ' );
			liwe.utils.notifier.show ( 'Modifiche permessi ai moduli ' + str + ' salvate', '', 1500 );
		};
	}
	user.admin._modules_perms.iterate ( function ( v, k )
		{
			f = liwe.form.get ( 'user-perms-' + k );
			if ( v.count () < 1 || ! f ) return;
			user.admin._set_perms_save ( k, type, cback, true );
			updated.push ( k );
		} );
	liwe.AJAX.start ( 'multi-user-perms', function ( resp ) { cback ( resp ); } );
};

user.admin._set_perms = function ( dest, id, type )
{
	var msg, curr;
	if ( user.admin._groups_on ) group.admin._clear_group_divs ();
	switch ( type )
	{
		case 'user':
			curr = user.admin._id_login [ id ];	
			msg = 'Settaggio permessi utente ( ' + curr + ' )';
			user.admin._curr_uid = id;
			if ( ! user.admin._groups_on ) 
			{
				user.admin._make_perms_form ( dest, id, type, msg );
				break;
			}
			if ( group.admin._u2g.get [ id ] )
			{
				user.admin._make_perms_form ( dest, id, type, msg );
				console.debug ( "cached" );
				break;
			}
			group.admin.get_user_groups ( id, function () { user.admin._make_perms_form ( dest, id, type, msg ); } );
			break;

		case 'group':
			if ( ! user.admin._groups_on ) break;
			curr = group.admin._id_name [ id ];	
			msg = 'Settaggio permessi gruppo ( ' + curr + ' )';
			group.admin._curr_gid = id;
			user.admin._make_perms_form ( dest, id, type, msg );
			break;
	};

};

user.admin._set_perms_save = function ( module_name, type, cback, multi )
{
	if ( ! cback )
	{
		cback = function ( resp )
			{ 
				user.admin._set_perms ( user.admin._right_top_div, user.admin._curr_uid ); 
				liwe.utils.notifier.show ( 'Modifiche permessi modulo ' + module_name + ' salvate', '', 1500 );
			};
	}

	var f = liwe.form.get ( "user-perms-" + module_name );
	var v = f.get_values ();
	var k = v.keys (), l = k.length, t;

	var res = [];

	v.iterate ( function ( v, k ) { if ( v == false || ! k.startsWith ( "perm:" ) ) return; res.push ( k.substr ( 5, 99 ) ); } );

	var vals = { 
			action: "system.admin.module_set_perms",
			module_name: v [ 'module_name' ],
			uid: v.get ( 'uid', v.get ( 'gid', '' ) ),
			perms: ':'.join ( res ),
			perms_type: type
			};	
	//single ajax request
	if ( ! multi )
	{
		user.admin.ajax ( vals, function ( resp ) { cback ( resp ); } );
		return;
	}
	//init multiple ajax requests. liwe.AJAX.start must be called within the calling function
	liwe.AJAX.add ( 'multi-user-perms', liwe.AJAX.url, vals ); 
};


user.admin._set_curr_user = function ( uid )
{
	user.admin._curr_uid = uid;
};

user.admin._get_modules = function ( uid )
{
	user.admin.ajax ( { action: "system.ajax.list_all_modules" }, function ( v )
		{
			var opts = [], mods = v [ 'modules' ];
			// var opts = [], mods = system.admin._modules;


			mods = mods.keys ();
			mods.sort ();
			//user.admin._modules.iterate ( function ( v ) { mods_lst.push ( v.value ) } );
			user.admin._modules_str = mods.join ( '|' );

			user.admin._modules_perms = v [ 'modules' ];

			mods.iterate ( function ( val , k  )
					{
						opts.push ( { label : val, value: val } );
					} );
			user.admin._modules = opts;
	} );
};

user.admin.create_layout = function ()
{
	$( 'system-content' , user.templates [ 'admin-layout' ] );
};
user.admin._init_templates = function ()
{
	user.admin.create_layout ();
	user.admin.acc_mods = new WWL.accordion ( 'modules' );
	WWL.accordion.set_duration ( 'modules', 200 );

	user.admin._admin_manager_init ( user.admin._left_top_am_div );

	user.admin._get_modules ();

	if ( user.admin._groups_on ) group.admin.init ();
};

user.admin.init = function ( group_admin )
{
	if ( group_admin ) user.admin._groups_on = true;
	function _list_usr ()
	{
		user.admin.admin_man.set_dest_div ( user.admin._left_top_am_div ); 
		if ( $( user.admin._right_top_div ) ) $( user.admin._right_top_div, '' );
		user.admin.list_users (); 
	};

	function _add_usr ()
	{ 
		user.admin.admin_man.set_dest_div ( user.admin._right_top_div ); 
		if ( $( user.admin._right_top_div ) ) $( user.admin._right_top_div, '' );
		user.admin.add (); 
	};
	

	var _acts = [ 
			{ func: _list_usr , img_src : '', label : 'Lista utenti', "class" : '' }, 
			{ func: _add_usr , img_src : '', label : 'Aggiungi utente', "class" : '' } 
		    ];

	if ( group_admin ) _acts.push ( { func: function () 
						{ 
							_list_usr ();
							group.admin.admin_man.set_dest_div ( user.admin._left_bot_am_div ); 
							if ( user.admin._groups_on ) group.admin._clear_group_divs ();
							if ( $( user.admin._right_top_div ) ) $( user.admin._right_top_div, '' );
							group.admin.add (); 
						} , img_src : '', label : 'Aggiungi gruppo', "class" : '' } ); 
	user.admin.register ( _acts );
	user.admin._init_templates ();
};
